package com.office.web.controller.common;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/dingtalk")
public class DingTalkController {

    @PostMapping("/send")
    public ResponseEntity<Map<String, Object>> sendToDingTalk(@RequestBody Map<String, String> payload) {
        String webhook = payload.get("webhook");
        String message = payload.get("message");
        String msgType = payload.getOrDefault("msgType", "text");
        boolean atAll = Boolean.parseBoolean(payload.getOrDefault("atAll", "false"));
        Map<String, Object> result = new HashMap<>();
        if (webhook == null || webhook.isEmpty() || message == null || message.isEmpty()) {
            result.put("success", false);
            result.put("msg", "Webhook地址和消息内容不能为空");
            return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
        }
        try {
            RestTemplate restTemplate = new RestTemplate();
            Map<String, Object> msgBody = new HashMap<>();
            msgBody.put("msgtype", msgType);
            if ("markdown".equals(msgType)) {
                Map<String, String> markdown = new HashMap<>();
                markdown.put("title", "通知");
                markdown.put("text", message);
                msgBody.put("markdown", markdown);
            } else {
                Map<String, String> text = new HashMap<>();
                text.put("content", message);
                msgBody.put("text", text);
            }
            Map<String, Object> at = new HashMap<>();
            at.put("isAtAll", atAll);
            msgBody.put("at", at);
            ResponseEntity<String> response = restTemplate.postForEntity(webhook, msgBody, String.class);
            if (response.getStatusCode().is2xxSuccessful()) {
                result.put("success", true);
            } else {
                result.put("success", false);
                result.put("msg", "钉钉返回异常: " + response.getBody());
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "请求钉钉失败: " + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
} 